import sys
import time

from influxdb import InfluxDBClient
from pathlib import Path

client = None

host='127.0.0.1'
port=8086
database='_internal'
username=''
password=''
dumpTables=''
output=''
format='json'
input = ''
limit = 1000

#连接数据库
def connectDB():
	print("connect influxDB.")
	print('ip:{}, port:{}, database:{}, user:{}, password:{}'.format(host, port, database, username, password))
	global client
	if (client != None):
		client.close()
		client = None
	if username == '':
		client = InfluxDBClient(host=host, port=port, database=database)
	else:
		client = InfluxDBClient(host=host, port=port, database=database, username=username, password=password)
	if client != None:
		print('connect influxdb success ip:{}, port:{}, database:{}'.format(host, port, database))
		return True
	else:
		print('connect influxdb failure ip:{}, port:{}, database:{}'.format(host, port, database))
		return False


def hostVerify():
	argv = sys.argv
	global host
	hostIndex = -1
	try:
		hostIndex = argv.index('-host')
	except ValueError:
		print("verify: not input host.")
	else:
		name = ''
		try:
			name = argv[hostIndex+1]
		except ValueError:
			print('verify: host address error ')
		else:
			host = name

def portVerify(): 
	argv = sys.argv
	global port
	portIndex = -1
	try:
		portIndex = argv.index('-port')
	except ValueError:
		print("verify: not input port.")
	else:
		iport = 0
		try:
			iport = argv[portIndex+1]
		except ValueError:
			print('verify: port port error ')
		else:
			port = iport

def databaseVerify(): 
	argv = sys.argv
	global database
	dbIndex = -1
	try:
		dbIndex = argv.index('-database')
	except ValueError:
		print("verify: not input batabase.")
	else:
		dbname = ''
		try:
			dbname = argv[dbIndex+1]
		except ValueError:
			print('database:{} error '.format(dbname))
		else:
			database = dbname
			
def usernameVerify(): 
	argv = sys.argv
	global username
	tableIndex = -1
	try:
		tableIndex = argv.index('-u')
	except ValueError:
		print("verify: not input username.")
	else:
		name = ''
		try:
			name = argv[tableIndex+1]
		except ValueError:
			print('verify: table:{} error '.format(table))
		else:
			username = name
			
def passwordVerify(): 
	argv = sys.argv
	global password
	passIndex = -1
	try:
		passIndex = argv.index('-p')
	except ValueError:
		print("verify: not input password.")
	else:
		passw = ''
		try:
			passw = argv[passIndex+1]
		except ValueError:
			print('verify: password error ')
		else:
			password = passw
			
def tablesVerify(): 
	argv = sys.argv
	global dumpTables
	tIndex = -1
	try:
		tIndex = argv.index('-table')
	except ValueError:
		print("verify: not input tables.")
	else:
		passw = ''
		try:
			ts = argv[tIndex+1]
		except ValueError:
			print('verify: password error ')
		else:
			dumpTables = ts

def outputVerify():
	argv = sys.argv
	global output
	oIndex = -1
	try:
		oIndex = argv.index('-o')
	except ValueError:
		print("verify: not input output.")
	else:
		out = ''
		try:
			out = argv[oIndex+1]
		except ValueError:
			print('verify: output error ')
		else:
			output = out
			path = Path(out)
			if path.is_dir() == False:
				print('please input right output dir.')
			
def inputVerify():
	argv = sys.argv
	global input
	iIndex = -1
	try:
		iIndex = argv.index('-i')
	except ValueError:
		print("verify: not input dir.")
	else:
		ins = ''
		try:
			ins = argv[iIndex+1]
		except ValueError:
			print('verify: input error ')
		else:
			input = ins
			path = Path(ins)
			if path.is_dir() == False:
				print('input dir is not exist.')
			
def formatVerify():
	argv = sys.argv
	global format
	fIndex = -1
	try:
		fIndex = argv.index('-format')
	except ValueError:
		print("verify: not input format.")
	else:
		fmt = ''
		try:
			fmt = argv[fIndex+1]
		except ValueError:
			print('verify: format error ')
		else:
			format = fmt

#获取当前时间字符串
def currentTimeStr():
	# time获取当前时间戳
	now = int(time.time())     # 1533952277
	timeArray = time.localtime(now)
	return time.strftime("%Y-%m-%d %H-%M-%S", timeArray)

def help():
	if len(sys.argv) == 1:
		print ('\n          *** wecome to influxdb dump/restore python tool. ***\n')
		print ('    -host     default localhost, influxDB ip.')
		print ('    -port     default 8086, influxDB port.')
		print ('    -u        default \'\', influxDB username.')
		print ('    -p        default \'\', influxDB password.')
		print ('    -o        default current dir, export table, output dir.')
		print ('    -i        default current dir, import json file dir.')
		print ('    -format   default json, import/export format.')
		print ('    -database *, DB name.')
		print ('    -table    default \'\', import/export tables, ie: tablea,tableb\n\n')
		return True
	else:
		return False
	
	
#校验输入参数
def verifyArgv():
	if help() == True:
		return False
	hostVerify()
	portVerify()
	databaseVerify()
	usernameVerify()
	passwordVerify()
	tablesVerify()
	outputVerify()
	formatVerify()
	inputVerify()
	return True

def dbClient():
	return client
	
def dbTables():
	return dumpTables
	
def ioFormat():
	return format
	
def outputDir():
	return output
	
def inputDir():
	return input
	
def limitSize():
	return limit